/**
* Copyright (c) By zengqh.
*
* This program is just for fun or demo, in the hope that it  
* will be useful, you can redistribute it and/or modify freely.
*
* Time: 2013/03/27
* File: ForBeginRenderPass.cpp
* Blog: http://www.cnblogs.com/zengqh/
**/

namespace HY
{
ForBeginRenderPass::ForBeginRenderPass(RenderSystem* render_sys)
: SceneRenderPass(render_sys)
{
	color_buffer_[0] = color_buffer_[1] = 0;
	depth_buffer_ = 0;
	render_targets[0] = render_targets[1] = 0;
	windows_render_target_ = 0;

	is_curr_front_buffer_ = true;
}

ForBeginRenderPass::~ForBeginRenderPass()
{
	
}

void ForBeginRenderPass::render(const RenderableList& render_list)
{
	/** check render buffer. */
	checkRenderBuffer();

	/** set render target. */
	render_sys_->setRenderTarget(render_targets[!is_curr_front_buffer_]);

	/** reset render state. */
	render_sys_->setRenderState(RenderState::FillMode, Fill::Solid);
	render_sys_->setRenderState(RenderState::CullMode, Cull::CCW);
	render_sys_->setRenderState(RenderState::ZEnable, 1);
	render_sys_->setRenderState(RenderState::BlendEnable, 0);
	render_sys_->setRenderState(RenderState::LineWidth, 1);
}

void ForBeginRenderPass::checkRenderBuffer()
{
	/** first set default render state. */
	windows_render_target_ = render_sys_->getRenderTarget();
	HY_ASSERT(windows_render_target_);

	IntVector2 render_target_size = windows_render_target_->getSize();

	/** setup front and back render target. */
	for (int i = 0; i < 2; ++i)
	{
		TextureBuffer*& tb = color_buffer_[i];
		if (!tb)
		{
			tb = = render_sys_->createTexture2D(render_target_size.x_,
				render_target_size.y_, TextureBuffer::R8G8B8);
		}

		if (!depth_buffer_)
		{
			depth_buffer_ = render_sys_->createTexture2D(render_target_size.x_,
				render_target_size.y_, TextureBuffer::D24);
		}

		RenderTargetBase*& rt = render_targets[i];
		if (!rt)
		{
			rt = render_sys_->createRenderTarget();
			rt->setColorTexture(color_buffer_[i]);
			rt->setDepthTexture(depth_buffer_);
		}
	}
}

void ForBeginRenderPass::swapRenderTarget()
{
	is_curr_front_buffer_ = !is_curr_front_buffer_;

	render_sys_->setRenderTarget(render_targets[!is_curr_front_buffer_]);
}
}